/***************************************************************************
 *   Copyright (C) 2007 by Alexandre Masselot,,,   *
 *   alex@alex-laptop   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU Library General Public License as       *
 *   published by the Free Software Foundation; either version 2 of the    *
 *   License, or (at your option) any later version.                       *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU Library General Public     *
 *   License along with this program; if not, write to the                 *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "scoredbestof.h"

namespace bol {

  ScoredBestOf::~ScoredBestOf()
  {
  }

  bool ScoredBestOf::add(const HasMetaScorePtr& scored){
    if(m_descriptor==NULL){
      m_descriptor=scored->score()->descriptor();
    }else{
      assert(m_descriptor==scored->score()->descriptor());
    }

    deque<HasMetaScorePtr>::iterator itpos=insertPos(scored);
    if(itpos==this->end()){
      push_back(scored);
    }else{
      insert(itpos, scored);
    }
    if(size()>max()){
      pop_back();
    }
// HACK I've no idea what this function is supposed to return
    return true; // otherwise this function will randomly return the result of pop_back, insert or pushbak
// TODO add a proper return value 
// probably, based on this->end and max, we can determin if a score was kept or thrown away
  }

  deque<HasMetaScorePtr>::iterator ScoredBestOf::insertPos(const HasMetaScorePtr& scored){
    for(deque<HasMetaScorePtr>::iterator it=this->begin(); it<this->end(); ++it){
      if((*it)->score()->mainScore()<scored->score()->mainScore()){
        return it;
      }
    }
    return this->end();
  }
  ostream& operator<<(ostream& out, const ScoredBestOf& bestof){
    for(deque<HasMetaScorePtr>::const_iterator it=bestof.begin(); it<bestof.end(); ++it){
      out<<((*it)->score()->mainScore())<<":"<< (*it) <<"\n";
    }
    out.flush();
    return out;
  }

}
